package cn.itcast.web;

import cn.itcast.pojo.*;
import cn.itcast.pojo.vo.RespBean;
import cn.itcast.service.FeedbackService;
import cn.itcast.service.UserService;
import cn.itcast.service.impl.orderServiceImpl;
import cn.itcast.util.DBUtils;
import cn.itcast.util.DataNumid;
import cn.itcast.util.ExpressServiceCodeEnum;
import cn.itcast.util.OutputStringController;
import cn.web.web_module.util.IconPath;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.sf.csim.express.service.CallExpressServiceTools;
import com.sf.csim.express.service.HttpClientUtil;
import com.sf.csim.express.service.IServiceCodeStandard;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.authc.Account;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.yaml.snakeyaml.scanner.Constant;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@RestController
@RequestMapping("/wxshop/feedback")
public class FeedbackController {

    @Resource
    private FeedbackService feedbackService;
    @Resource
    private UserService userService;
    @Resource
    orderServiceImpl orderService;

    @Resource
    OutputStringController osc;

    @ApiOperation("添加留言")
    @PostMapping("addFeedback")
    public RespBean addFeedback(@RequestBody Map<String, String> map) {
        String openId = map.get("openId");
        if (openId == null) return RespBean.error("请先登录！");
        String feedbackContent = map.get("feedbackContent");
        if (StringUtils.isEmpty(feedbackContent)) return RespBean.error("请输入内容！");

        user user = userService.findUserInfo(openId);
        if (user == null) return RespBean.error("请先登录！");
        Feedback feedback = new Feedback();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        feedback.setOpenid(openId)
                .setUsername(user.getUserName())
                .setUserphone(user.getUserPhone())
                .setContent(feedbackContent)
                .setContenttime(sdf.format(new Date()));
        if (feedbackService.addFeedback(feedback)) {
            return RespBean.success("反馈成功！");
        }
        return RespBean.error("反馈失败！请稍后再试");
    }

    @ApiOperation("查看用户所有的留言")
    @GetMapping("getFeedbackList")
    public RespBean listFeedback(String openId) {
        return RespBean.success(null, feedbackService.feedbackList(openId));
    }


    /**
     * @Description: 顺丰下单
     * @auther: 欧阳
     * @date: 14:51 2021/10/28
     * @param: [map]
     * @return: map
     */
    @ApiOperation("顺丰快递下单")
    @PostMapping(value = "/sfadd", produces = "text/html;charset=utf-8")
    public String sfadd(@RequestBody Map<String, String> order) throws InterruptedException, UnsupportedEncodingException {
        log.debug("顺丰快递下单了。。。");
        sforder sforder = new sforder();
        sforder.setLanguage("zh_CN");
        sforder.setOpenid(order.get("openId"));
        sforder.setOrdertime(order.get("ordertime"));
        String sendStartTm = order.get("sendStartTm");
        sforder.setSendStartTm(sendStartTm);
        sforder.setIsDocall(1); //上门1,不上门0
        sforder.setMonthlyCard("7690288407");
        sforder.setPayMethod(2);//1:寄方付2:收方付3:第三方付

        HashMap cargoDetailslist = new HashMap();
        List mapcontactInfoList = new ArrayList<>();
        HashMap sendList = new HashMap();
        HashMap saveList = new HashMap();
        List cargoList = new ArrayList<>();

        cargoDetailslist.put("unit", "公斤");
        cargoDetailslist.put("weight", "5.0");
        cargoDetailslist.put("currency", "HKD");
        cargoDetailslist.put("name", "衣服");
        cargoDetailslist.put("sourceArea", "CHN");
        cargoList.add(cargoDetailslist);
        sforder.setCargoDetails(cargoList);
        sforder.setUnit("公斤");
        sforder.setWeight(5.0);
        sforder.setCurrency("HKD");
        sforder.setName("衣服");
        sforder.setSourceArea("CHN");

        //寄件人信息
        sendList.put("address", order.get("send_address"));
        sendList.put("contact", order.get("send_contact"));
        sendList.put("tel", order.get("send_tel"));
        sendList.put("contactType", "1");
        sendList.put("postCode", order.get("send_postCode"));
        sendList.put("country", "CN");
        sforder.setSend_address(order.get("send_address"));
        sforder.setSend_contact(order.get("send_contact"));
        sforder.setSend_tel(order.get("send_tel"));
        sforder.setSend_contactType("1");
        sforder.setSend_postCode(order.get("send_postCode"));
        sforder.setSend_country("CN");

        //收货人信息
        saveList.put("address", "广东省东莞市南城街道绿色路2号世纪城150栋3单元119室（大黄牛）");
        saveList.put("company", "大黄牛");
        saveList.put("contact", "黄小姐");
        saveList.put("contactType", "2");
        saveList.put("country", "CN");
        saveList.put("tel", "18819272959");
        mapcontactInfoList.add(sendList);
        mapcontactInfoList.add(saveList);

        sforder.setContactInfoList(mapcontactInfoList);
        sforder.setSave_address("广东省东莞市南城街道绿色路2号世纪城150栋3单元119室（大黄牛）");
        sforder.setSave_company("大黄牛");
        sforder.setSave_contact("黄小姐");
        sforder.setSave_country("CN");
        sforder.setSave_tel("18819272959");
        sforder.setOrderstate("待上门");


        //生成当前时间随机数为orderid
        SimpleDateFormat myFmt = new SimpleDateFormat("yyMMddHHmmss");
        Date date = new Date();
        sforder.setOrderId(myFmt.format(date));

        String json = JSON.toJSONString(sforder);
        System.out.println(json);

        String CLIENT_CODE = "HHMa2Chq2S";  //此处替换为您在丰桥平台获取的顾客编码
        String CHECK_WORD = "gZYjyADedI5tfN3zpAiaSZCrOarhEled";//此处替换为您在丰桥平台获取的校验码
        //沙箱环境的地址 -PRO
        //String CALL_URL_BOX ="https://sfapi-sbox.sf-express.com/std/service";
        //生产环境的地址 -PRO
        String CALL_URL_PROD = "https://sfapi.sf-express.com/std/service";


        IServiceCodeStandard testService = ExpressServiceCodeEnum.EXP_RECE_CREATE_ORDER; //下订单
        CallExpressServiceTools client = CallExpressServiceTools.getInstance();
        // set common header
        Map<String, String> params = new HashMap<String, String>();
        String timeStamp = String.valueOf(System.currentTimeMillis());
        //String msgData =client.packageMsgData(testService);

        params.put("partnerID", CLIENT_CODE);  // 顾客编码 ，对应丰桥上获取的clientCode
        params.put("requestID", UUID.randomUUID().toString().replace("-", ""));
        params.put("serviceCode", testService.getCode());// 接口服务码
        params.put("timestamp", timeStamp);
        params.put("msgData", json);
        params.put("msgDigest", client.getMsgDigest(json, timeStamp, CHECK_WORD));

        // System.out.println(params.get("requestID"));
        long startTime = System.currentTimeMillis();

        System.out.println("====调用请求：" + params.get("msgData"));
        String result = HttpClientUtil.post(CALL_URL_PROD, params);

        System.out.println("====调用丰桥的接口服务代码：" + String.valueOf(testService.getCode()) + " 接口耗时：" + String.valueOf(System.currentTimeMillis() - startTime) + "====");
        System.out.println("===调用地址 ===" + CALL_URL_PROD);
        System.out.println("===顾客编码 ===" + CLIENT_CODE);
        System.out.println("===返回结果：" + result);

        //String转换json对象.
        JSONObject object = JSON.parseObject(result);
        //取值sfid
        //String success=object.getJSONObject("apiResultData").get("success").toString();


        String success = object.getJSONObject("apiResultData").getJSONObject("msgData").getJSONArray("waybillNoInfoList").toString();

        JSONObject JSONObject2 = object.getJSONObject("apiResultData").getJSONObject("msgData");


        JSONArray jsonArray2 = JSONObject2.getJSONArray("waybillNoInfoList");

        JSONObject jsonObject2 = jsonArray2.getJSONObject(0);
        String sfid = jsonObject2.get("waybillNo").toString();
        sforder.setMessage(sfid);


        System.out.println(sfid);

        if (sfid != null) {
            int sfadd = orderService.sfadd(sforder);
        }
        return result;
    }

    /**
     * @Description: 顺丰openid查询订单
     * @auther: 欧阳
     * @date: 14:51 2021/10/28
     * @param: [map]
     * @return: map
     */
    @ApiOperation("顺丰openid查询订单")
    @PostMapping(value = "/idsfquery", produces = "text/html;charset=UTF-8;")
    public String idsfquery(@RequestBody Map<String, String> map) {
        String openid = map.get("openid");
        List<sforder> sfidquerylist = orderService.listsfquery(openid);
        String json = JSON.toJSONString(sfidquerylist);
        return json;
    }


    @ApiOperation("顺丰openid查询最新一条订单")
    @PostMapping(value = "/idsftoponequery", produces = "text/html;charset=UTF-8;")
    public String idsftoponequery(@RequestBody Map<String, String> map) {
        log.debug("顺丰openid查询最新一条订单" + map.get("openid"));
        String openid = map.get("openid");
        sforder sforder = orderService.toponeidquery(openid);
        String json = JSON.toJSONString(sforder);
        return json;
    }

    @ApiOperation("顺丰取消订单")
    @PostMapping(value = "/sfcancel", produces = "text/html;charset=UTF-8;")
    public String sfcancel(@RequestBody Map<String, String> map) throws UnsupportedEncodingException {
        log.debug("顺丰取消订单" + map.get("openid"));
        String dealType = "2"; //1确认.2取消订单
        String orderid = map.get("orderid");
        sforder sforder = new sforder();
        sforder.setOrderId(orderid);
        Map<String, String> mapdata = new HashMap<>();
        mapdata.put("dealType", dealType);
        mapdata.put("orderid", orderid);
        String json = JSON.toJSONString(mapdata);

        String CLIENT_CODE = "HHMa2Chq2S";  //此处替换为您在丰桥平台获取的顾客编码
        String CHECK_WORD = "gZYjyADedI5tfN3zpAiaSZCrOarhEled";//此处替换为您在丰桥平台获取的校验码
        //沙箱环境的地址 -PRO
        //String CALL_URL_BOX ="https://sfapi-sbox.sf-express.com/std/service";
        //生产环境的地址 -PRO
        String CALL_URL_PROD = "https://sfapi.sf-express.com/std/service";


        IServiceCodeStandard testService = ExpressServiceCodeEnum.EXP_RECE_UPDATE_ORDER; //取消订单
        CallExpressServiceTools client = CallExpressServiceTools.getInstance();
        // set common header
        Map<String, String> params = new HashMap<String, String>();
        String timeStamp = String.valueOf(System.currentTimeMillis());
        //String msgData =client.packageMsgData(testService);

        params.put("partnerID", CLIENT_CODE);  // 顾客编码 ，对应丰桥上获取的clientCode
        params.put("requestID", UUID.randomUUID().toString().replace("-", ""));
        params.put("serviceCode", testService.getCode());// 接口服务码
        params.put("timestamp", timeStamp);
        params.put("msgData", json);
        params.put("msgDigest", client.getMsgDigest(json, timeStamp, CHECK_WORD));

        // System.out.println(params.get("requestID"));
        long startTime = System.currentTimeMillis();

        System.out.println("====调用请求：" + params.get("msgData"));
        String result = HttpClientUtil.post(CALL_URL_PROD, params);

        System.out.println("====调用丰桥的接口服务代码：" + String.valueOf(testService.getCode()) + " 接口耗时：" + String.valueOf(System.currentTimeMillis() - startTime) + "====");
        System.out.println("===调用地址 ===" + CALL_URL_PROD);
        System.out.println("===顾客编码 ===" + CLIENT_CODE);
        System.out.println("===返回结果：" + result);

        //String转换json对象.
        JSONObject object = JSON.parseObject(result);

        String success = object.getJSONObject("apiResultData").get("success").toString();


        if (success == "true") {
            int up = orderService.sfcancelmapp(sforder);
        }

        return result;
    }


    @ApiOperation("顺丰删除已取消订单")
    @PostMapping(value = "/sfdeleteorderid", produces = "text/html;charset=UTF-8;")
    public String sfdeleteorderid(@RequestBody Map<String, String> map) {
        String orderid = map.get("orderid");
        Map<String, String> status = new HashMap<>();
        sforder sforder = new sforder();
        sforder.setOrderId(orderid);
        int res = orderService.deletesfopenidmapp(sforder);
        if (res == 1) {
            status.put("status", "succeed");
        } else {
            status.put("status", "error");
        }
        String json = JSON.toJSONString(status);
        return json;
    }

    @ApiOperation("顺丰订单状态推送")
    @PostMapping(value = "/orderState", produces = "text/html;charset=UTF-8;")
    public String OrderState(@RequestBody String content) {
        net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(content);
        Map<String, String> returns = new HashMap<>();
        JSONArray stirngstr = new JSONArray();
        net.sf.json.JSONArray jsonArray1 = jsonObject.getJSONArray("orderState");
        net.sf.json.JSONObject A1 = jsonArray1.getJSONObject(0);

        sforder sforder = new sforder();

        String res = A1.get("orderStateCode").toString();
        if (A1.get("orderNo").toString() != null) {
            System.out.println(jsonObject);
            //客户订单号
            String orderNo = A1.get("orderNo").toString();
            sforder.setOrderId(orderNo);
            //顺丰运单号
            String waybillNo = A1.get("waybillNo").toString();
            //订单状态
            String orderStateCode = A1.get("orderStateCode").toString();
            switch (orderStateCode) {
                case "04":
                    sforder.setOrderstate("调度失败/等待");
                    break; //可选
                case "04-40001":
                    sforder.setOrderstate("调度成功+收派员信息");
                    break; //可选
                case "04-40037":
                    sforder.setOrderstate("下单已接收");
                    break; //可选
                case "04-40002-40021":
                    sforder.setOrderstate("电话号码异常(电话错误/空号/停机)");
                    break; //可选
                case "04-40002-40022":
                    sforder.setOrderstate("无法进入客户处,且客户不愿出来");
                    break; //可选
                case "04-40002-40004":
                    sforder.setOrderstate("暂未联系上客户(电话无人接听/无法接通/关机)");
                    break; //可选
                case "04-40002-40005":
                    sforder.setOrderstate("经客户同意,更改收派时间");
                    break; //可选
                case "04-40002-40027":
                    sforder.setOrderstate("天气原因,延误收派件");
                    break; //可选
                case "04-40002-40028":
                    sforder.setOrderstate("交通原因,延误收派件");
                    break; //可选
                case "04-40002-40031":
                    sforder.setOrderstate("不符合收件要求,无法揽收");
                    break; //可选
                case "04-40002-40014":
                    sforder.setOrderstate("客户取消寄件");
                    break; //可选
                case "04-40002-40015":
                    sforder.setOrderstate("客户重复下单");
                    break; //可选
                case "04-40002-40016":
                    sforder.setOrderstate("下错单需转单");
                    break; //可选
                case "04-40002-40035":
                    sforder.setOrderstate("工作量过大,延误收派件");
                    break; //可选
                case "04-40002-40036":
                    sforder.setOrderstate("重货需转单");
                    break; //可选
                case "04-40045-1000":
                    sforder.setOrderstate("调度取消订单");
                    break; //可选
                case "00-2000":
                    sforder.setOrderstate("客户已取消订单");
                    break; //可选
                case "05-40003":
                    sforder.setOrderstate("已正常收件状态");
                    break; //可选
                case "00-40065":
                    sforder.setOrderstate("订单超时结束");
                    break; //可选
            }

            //收件员工工号
            String empCode = A1.get("empCode").toString();
            sforder.setEmpCode(empCode);
            //收件员手机号
            String empPhone = A1.get("empPhone").toString();
            sforder.setEmpPhone(empPhone);
            //最晚上门时间
            String lastTime = A1.get("lastTime").toString();
            sforder.setLastTime(lastTime);
            //客户预约时间
            String bookTime = A1.get("bookTime").toString();
        }
        String ret = "";
        int updateorder = orderService.updatesforder(sforder);
        if (updateorder == 1) {
            //推送接口必须返回响应
            returns.put("success", "true");
            returns.put("code", "0");
            returns.put("msg", "");
            stirngstr.add(returns);
            ret = stirngstr.toJSONString();
        } else {
            returns.put("success", "false");
            returns.put("msg", "订单状态接收异常");
            stirngstr.add(returns);
            ret = stirngstr.toJSONString();
        }

        return ret;
    }


    @ApiOperation("清单运费推送接口")
    @PostMapping(value = "/ListingPush", produces = "text/html;charset=UTF-8;")
    public String ListingPush(@RequestParam String sign, @RequestParam String content) {
        net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(content);
        sforder sforder = new sforder();
        System.out.println(jsonObject.get("orderNo"));  //订单号
        System.out.println(jsonObject.get("meterageWeightQty"));    //包裹计费重量 单位kg
        System.out.println(jsonObject.get("quantity"));     //数量
        sforder.setWeight(jsonObject.getDouble("meterageWeightQty"));
        sforder.setCount(jsonObject.getInt("quantity"));
        sforder.setOrderId(jsonObject.get("orderNo").toString());

        net.sf.json.JSONArray A1 = jsonObject.getJSONArray("feeList");
        String feeIndType = "";
        Double sum = null;
        for (int i = 0; i < A1.size(); i++) {
            switch (A1.getJSONObject(i).get("feeTypeCode").toString()) {
                case "1":
                    feeIndType = "主运费";
                    break;
                case "2":
                    feeIndType = "其他费用";
                    break;
                case "3":
                    feeIndType = "保费";
                    break;
                case "4":
                    feeIndType = "代收货款服务费";
                    break;
                case "5":
                    feeIndType = "代收货款";
                    break;
            }
            System.out.println(feeIndType + ":" + A1.getJSONObject(i).get("feeAmtInd"));
            Double aafeeAmtInd = A1.getJSONObject(i).getDouble("feeAmtInd");
            sum = aafeeAmtInd + i;
            System.out.println("当前xx:" + aafeeAmtInd + ":aa" + sum);
        }
        System.out.println("合：" + sum);
        sforder.setFreight(sum);
        int up = orderService.updatesffreightmapp(sforder);
        return content;
    }


    @ApiOperation("路由推送")
    @PostMapping(value = "/routepush", produces = "application/json;charset=UTF-8;")
    public String Routepush(@RequestBody String content) {
        JSONArray stirngstr = new JSONArray();
        sforder sforder = new sforder();
        account account = new account();
        Map<String, String> returns = new HashMap<>();
        net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(content);
        net.sf.json.JSONObject json = jsonObject.getJSONObject("Body");
        net.sf.json.JSONArray A1 = json.getJSONArray("WaybillRoute");
        net.sf.json.JSONObject jsonObject2 = A1.getJSONObject(0);

        //解析json
        sforder.setAcceptAddress(jsonObject2.get("acceptAddress").toString());
        sforder.setOrderId(jsonObject2.get("orderid").toString());
        sforder.setAcceptTime(jsonObject2.get("acceptTime").toString());
        sforder.setRemark(jsonObject2.get("remark").toString());
        String orderid = jsonObject2.get("orderid").toString();
        sforder.setOrderId(jsonObject2.get("orderid").toString());

        cn.itcast.pojo.sforder sf = orderService.selectorderid(orderid);
        System.out.println("重量：====" + sf.getWeight());
        account.setOpenId(sf.getOpenid());

        //查询状态码是否成功签收 80 等于签收
        String opcode = jsonObject2.get("opCode").toString();
        sforder.setOpCode(jsonObject2.get("opCode").toString());
        Double aaa = 30.0;
        //判断订单状态是否是签收8000代码
        if (opcode.equals("8000")) {
            //签收判断重量是否符合环保金
            if (sf.getWeight() >= 20.0 && sf.getWeight() <= 30.0) {
                //查询当前opeid这人账户多少钱
                account accounts = orderService.selemoneycount(account);
                Double countmoneyBalance = accounts.getAccountMoneyBalance() + 5.00;
                log.debug("几块钱？：===" + countmoneyBalance);
                accounts.setAccountMoneyBalance(countmoneyBalance);

                earnings earnings = new earnings(); //收益记录
                earnings.setNum(5.00);
                earnings.setOpenid(account.getOpenId());
                earnings.setAccountId(accounts.getAccountId());
                earnings.setName(account.getAccountName());
                earnings.setSource("快递回收");
                earnings.setState("已到账");
                earnings.setEarningsExplain("环保金结算");

                orderService.updatemoney(accounts);//修改账户总额
                orderService.addearnings(earnings);//新增快递上门回收
            }
            if (sf.getWeight() >= 30.1 && sf.getWeight() <= 40.0) {
                //查询当前opeid这人账户多少钱
                account accounts = orderService.selemoneycount(account);
                Double countmoneyBalance = accounts.getAccountMoneyBalance() + 10.00;
                log.debug("几块钱？：===" + countmoneyBalance);
                account.setAccountMoneyBalance(countmoneyBalance);

                earnings earnings = new earnings(); //收益记录
                earnings.setNum(10.00);
                earnings.setOpenid(account.getOpenId());
                earnings.setAccountId(accounts.getAccountId());
                earnings.setName(account.getAccountName());
                earnings.setSource("快递回收");
                earnings.setState("已到账");
                earnings.setEarningsExplain("环保金结算");

                orderService.updatemoney(accounts);//修改账户总额
                orderService.addearnings(earnings);//新增快递上门回收
            }
        } else {
            System.out.println("神马都没有");
        }

        int upd = orderService.updateRoutepush(sforder);
        String ret = "";
        if (upd == 1) {
            //推送接口必须返回响应
            returns.put("return_code", "0000");
            returns.put("return_msg", "成功");
            stirngstr.add(returns);
            ret = stirngstr.toJSONString();
        } else {
            //推送接口必须返回响应
            returns.put("return_code", "1000");
            returns.put("return_msg", "系统异常");
            stirngstr.add(returns);
            ret = stirngstr.toJSONString();
        }

        return ret;
    }


    @ApiOperation("上传营业执照图片")
    @PostMapping("updateIcon")
    public String uploadIcon(HttpServletRequest request, MultipartFile file) throws IOException {
        //返回结果
        String results = "";

        //将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        //检查form中是否有enctype="multipart/form-data"
        if (multipartResolver.isMultipart(request)) {
            //将request变成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            //获取multiRequest 中所有的文件名
            Iterator iter = multiRequest.getFileNames();

            while (iter.hasNext()) {
                //一次遍历所有文件
                MultipartFile files = multiRequest.getFile(iter.next().toString());
                if (files != null) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                    String newDate = sdf.format(new Date());
                    //服务器存储图片地址
                    //服务器地址：“/usr/tomcat/images/dhn/icon/orderItem”
                    //String filePath= "D:/Desktop/icon/orderItem/"+newDate+"/"+file.getOriginalFilename();
//					String filePath= "/usr/tomcat/images/dhn/icon/orderItem/"+newDate+"/"+file.getOriginalFilename();	//松注释
                    //String filePath="/usr/tomcat/images/wxshop/evaluate/"+request.getParameter("openId")+"/"+file.getOriginalFilename();
//					File files=new File("/usr/tomcat/images/dhn/icon/orderItem/"+newDate);	//松注释

                    String filePath = IconPath.ICONPATH + "icon/type/" + newDate + "/" + files.getOriginalFilename();
                    File filess = new File(IconPath.ICONPATH + "icon/type/" + newDate);
                    //File files=new File("D:/Desktop/icon/orderItem/"+newDate);
                    if (!filess.exists()) {//如果文件夹不存在
                        filess.mkdir();//创建文件夹
                    }
                    //数据库存放访问地址
                    //String path="D:/Desktop/icon/orderItem/"+newDate+"/"+file.getOriginalFilename();
                    String path = "https://www.dhnep.cn:8181/dhn/icon/type/" + newDate + "/" + file.getOriginalFilename();
                    results = path;
                    try {
                        //上传图片至服务器
                        file.transferTo(new File(filePath));
                        log.debug("上传成功");
                    } catch (IOException e) {
                        log.debug("上传失败");
                        e.printStackTrace();
                    }


                }

            }

        }

        return results;
    }


    /**
     * @Description: 德邦快递下单
     * @auther: 欧阳
     * @date: 14:51 2021/11/30
     * @param: [map]
     * @return: map
     */
    @ApiOperation("德邦快递下单")
    @PostMapping(value = "/dbadd", produces = "text/html;charset=utf-8")
    public String dbadd(@RequestBody Map<String, String> order) throws UnsupportedEncodingException {
        log.debug("德邦快递下单。。。。");
        String companyCode ="EWBSTHBKJG";       //核算第三方接入商的公司编码
        String appkey ="cc20e8ce81058dd70e27795cc9754424";      //appkey
        String openId=order.get("openId");
        Dborder dborder =new Dborder();
        String res="";
        HashMap cargoDetailslist = new HashMap();
        dborder.setCompanyCode("EWBSTHBKJG");   //公司编码
          //客户编码/月结账号
        dborder.setCustomerCode("863038974");
        //logisticID
        SimpleDateFormat myFmt = new SimpleDateFormat("yyMMddHHmmss");
        Date date = new Date();
        dborder.setLogisticID("GWDE"+myFmt.format(date));
        dborder.setOrderType("1");       //下单模式     详细类型德邦文档
        dborder.setTransportType("ZBTH");     //运输方式
        dborder.setPayType("2");               //支付方式

        //下单时间
        SimpleDateFormat myconm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String gmtstring=myconm.format(date);
        dborder.setGmtCommit(gmtstring);


        Map<String,String> packageinfolist = new HashMap<>();
        packageinfolist.put("cargoName","旧衣服");
        packageinfolist.put("deliveryType","3");
        packageinfolist.put("totalNumber","2");
        packageinfolist.put("totalVolume","0.1");
        packageinfolist.put("totalWeight","1");
        packageinfolist.put("packageService","纤");
        dborder.setPackageInfo(packageinfolist);




        //收货人信息
        Map<String,String> senderlist = new HashMap<>();
        senderlist.put("address","广东省东莞市南城街道绿色路2号世纪城150栋3单元119室（大黄牛）");
        senderlist.put("city","东莞市");
        senderlist.put("county","南城区");
        senderlist.put("mobile","18819272959");
        senderlist.put("name","大黄牛");
        senderlist.put("province","广东");
        dborder.setSender(senderlist);





        //寄件人信息
        Map<String,String> receiverlist = new HashMap<>();
        receiverlist.put("address",order.get("address"));
        receiverlist.put("city",order.get("address"));
        receiverlist.put("county",order.get("county"));
        receiverlist.put("mobile",order.get("mobile"));
        receiverlist.put("name",order.get("name"));
        receiverlist.put("province",order.get("province"));
        dborder.setReceiver(receiverlist);

        String json= JSON.toJSONString(dborder);
        String response = DBUtils.postHttp("http://dpsanbox.deppon.com/sandbox-web/dop-standard-ewborder/createOrderNotify.action", json, companyCode, appkey);
        System.out.println(response);
        log.debug(response);

        JsonParser jp = new JsonParser();
        JSONObject jsobjec=JSONObject.parseObject(response);
        String result=jsobjec.get("result").toString();     //返回状态
        String mailNo=jsobjec.get("mailNo").toString();     //返回单号

        //判断快递是否成功成功保存数据库
        if (result.equals("true")){
            dborder.setMailNo(mailNo);
            dborder.setCargoName("旧衣服");
            dborder.setDeliveryType("3");
            dborder.setTotalNumber("2");
            dborder.setTotalVolume("0.1");
            dborder.setTotalWeight("1");
            dborder.setPackageService("纤");
            dborder.setCustOrderNo(dborder.getLogisticID());
            //收货人保存数据库
            dborder.setSender_address("广东省东莞市南城街道绿色路2号世纪城150栋3单元119室（大黄牛）");
            dborder.setSender_city("东莞市");
            dborder.setSender_county("南城区");
            dborder.setSender_mobile("18819272959");
            dborder.setSender_name("大黄牛");
            dborder.setSender_province("广东");

            //发货人
            receiverlist.put("address",order.get("address"));
            receiverlist.put("city",order.get("address"));
            receiverlist.put("county",order.get("county"));
            receiverlist.put("mobile",order.get("mobile"));
            receiverlist.put("name",order.get("name"));
            receiverlist.put("province",order.get("province"));

            dborder.setReceiver_address(order.get("address"));
            dborder.setReceiver_city(order.get("address"));
            dborder.setReceiver_county(order.get("county"));
            dborder.setReceiver_mobile(order.get("mobile"));
            dborder.setReceiver_name(order.get("name"));
            dborder.setReceiver_province(order.get("province"));
            dborder.setReceiver(null);
            dborder.setSender(null);
            dborder.setOpenId(openId);
            dborder.setOrderstatus("已下单");  //订单状态

            boolean adddb=feedbackService.adddb(dborder);
            System.out.println(dborder);
        }


        return response;

    }


    /**
     * @Description: 德邦取消下单
     * @auther: 欧阳
     * @date: 14:51 2021/11/30
     * @param: [map]
     * @return: map
     */
    @ApiOperation("德邦取消下单")
    @PostMapping(value = "/dbcancel", produces = "text/html;charset=utf-8")
    public String dbcancel(@RequestBody Map<String, String> order) throws UnsupportedEncodingException {
        log.debug("德邦快递下单。。。。");
        String companyCode ="EWBSTHBKJG";       //核算第三方接入商的公司编码
        String appkey ="cc20e8ce81058dd70e27795cc9754424";      //appkey
        JsonParser jp = new JsonParser();
        Dborder dborder =new Dborder();
        String id =order.get("id");
        int idint=Integer.valueOf(id).intValue();
        dborder.setId(idint);
        dborder.setCompanyCode("EWBSTHBKJG");   //公司编码

        //logisticID
        SimpleDateFormat myFmt = new SimpleDateFormat("yyMMddHHmmss");
        Date date = new Date();
        //撤销时间
        SimpleDateFormat myconm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String gmtstring=myconm.format(date);
        String mailNo=order.get("mailNo");
        Map<String,String>mapjson=new HashMap<>();
        mapjson.put("cancelTime",gmtstring);    //时间
        mapjson.put("mailNo",mailNo);
        mapjson.put("remark","撤销订单");
        mapjson.put("logisticCompanyID","DEPPON");

        String json= JSON.toJSONString(mapjson);
        String response = DBUtils.postHttp("http://dpsanbox.deppon.com/sandbox-web/standard-order/cancelOrder.action", json, companyCode, appkey);
        System.out.println(response);
        log.debug(response);

        JSONObject jsobjec=JSONObject.parseObject(response);
        String result=jsobjec.get("result").toString();
        if (result.equals("true")){

            boolean updatesele =feedbackService.updateopenidstatus(dborder);
        }
        return response;

    }


    /**
     * @Description: 德邦查询个人订单
     * @auther: 欧阳
     * @date: 14:51 2021/12/02
     * @param: [map]
     * @return: map
     */
    @ApiOperation("德邦查询个人订单")
    @PostMapping(value = "/selectdbopenid", produces = "text/html;charset=utf-8")
    public String selectdbopenid(@RequestBody Map<String, String> order){
        log.debug("openid查询个人订单德邦快递。。");
        String openid=order.get("openId");
        List<Dborder>dblist= feedbackService.openidselectdb(openid);
        String json = JSON.toJSONString(dblist);
        return json;
    }


}






